package com.ruoyi.team.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.team.domain.*;
import com.ruoyi.team.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.team.mapper.GoodsStoreMapper;

/**
 * 物品库存Service业务层处理
 *
 * @author khr
 * @date 2022-11-28
 */
@Service
public class GoodsStoreServiceImpl extends ServiceImpl<GoodsStoreMapper, GoodsStore> implements IGoodsStoreService {

    @Autowired
    private IStockBillItemService stockBillItemService;
    @Autowired
    private IStockBillService     stockBillService;

    /**
     * 查询物品库存列表
     *
     * @param goodsStore 物品库存
     * @return 物品库存
     */
    @Override
    public List<GoodsStore> selectGoodsStoreList(GoodsStore goodsStore) {
        List<GoodsStore> goodsStoreList = getBaseMapper().selectGoodsStoreJoinGoodsAndGoodsCategory(goodsStore);

        for (GoodsStore currentGoodsStore : goodsStoreList) {
            // 得到当前 GoodsStore对象的物品ID, 并基于 物品ID 去查询出入库单集合(StockBillItem)
            List<StockBillItem> stockBillItemList = stockBillItemService.getBaseMapper().selectList(Wrappers.lambdaQuery(StockBillItem.class).eq(StockBillItem::getGoodsId, currentGoodsStore.getGoodsId()));

            if (stockBillItemList == null) {
                break;
            }

            for (StockBillItem stockBillItem : stockBillItemList) {
                // 基于 入库单集合的详情表ID 去查询具体的详情表, 并只留下 仓库=当前GoodsStore对象的仓库
                StockBill stockBill = stockBillService.getById(stockBillItem.getBillId());

                // 如果仓库相等 => 是对当前 GoodsStore 进行得到进入库
                if (stockBill.getStoreId().equals(currentGoodsStore.getStoreId())) {
                    // 进入库类型
                    currentGoodsStore.setType(stockBill.getType());
                    // 进入库的数量
                    currentGoodsStore.setInOutAmounts(stockBillItem.getAmounts());
                    // 此次进入库商品的价格
                    currentGoodsStore.setPrice(stockBillItem.getPrice());
                    // 此次进入的时间
                    currentGoodsStore.setInOutBusiDate(stockBill.getBusiDate());
                }
            }
        }

        return goodsStoreList;
    }

    @Override
    public GoodsStore selectStoreGoods(Long id) {
        return getBaseMapper().selectStoreGoods(id);
    }
}
